from anycloud import config
from anycloud.engine.base import Engine
from anycloud.engine.ipython import IPythonEngine
from anycloud.engine import ec2ipy1
from anycloud.error import NotFoundError

class EC2Engine(Engine):
    _params = (
        config.StringParameter(
            'ec2.ec2config', 'Config file with EC2 credentials and keys.',
            default='ec2config.txt'
        ),
        config.IntParameter(
            'ec2.num_instances', 'Number of instances to create.',
            default=1
        ),
        config.IntParameter(
            'ec2.ami', 'Amazon Machine Image (AMI) to use.',
            default='ami-66a3470f'
        ),
    )

    def __init__(self, **kwargs):
        super(EC2Engine, self).__init__(**kwargs)
        self.ec2 = ec2ipy1.EC2Cluster(self.ec2config)
        self.start()

    def __del__(self):
        self.stop()

    def start(self):
        self.ec2.create_instances(self.ami, self.num_instances)
        self.ec2.start_ipython1(engine_on_controller=True)
        self.ipyengine = IPythonEngine(self.ec2.task_controller_url) 

    def stop(self):
        self.ec2.terminate_instances()

    def submit(self, tasks):
        return self.ipyengine.submit(tasks)

    def retrieve(self, tasks):
        return self.ipyengine.retrieve(tasks)

    def execute(self, tasks):
        return self.ipyengine.execute(tasks)
 


